package com.user.gateway.filter;

import com.shop.utils.common.enums.Jwt;
import com.shop.utils.common.enums.Message;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

@Component
@Slf4j
public class UserWebMvcConfiguration implements Ordered, GlobalFilter{

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        if (request.getURI().getPath().contains("/user/login")) {
            return chain.filter(exchange);
        }
        if (request.getURI().getPath().contains("/user/wares")) {
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst(Jwt.WeChat_Jwt_Key.getName());
        log.info("token:{}",token);
        if (StringUtils.isBlank(token)) {
            log.info("token为空");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try {
            Claims body = Jwts.parser()
                    .setSigningKey(Jwt.WeChat_Jwt_Key.getKey())
                    .parseClaimsJws(token).getBody();
            body.getExpiration().before(new Date());
            if (body.getExpiration().getTime()-System.currentTimeMillis()<300000){
                log.info("过期token");
                return response.setComplete();
            }
            log.info("解码成功，body:{}",body);
            Integer userId = (Integer) body.get(Message.User_Id);
            log.info("userId解析:{}",userId);
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {httpHeaders.add("userId",userId+"");}).build();
            exchange.mutate().request(serverHttpRequest).build();
        }catch (Exception e){
            e.printStackTrace();
            log.info("token解码错误");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        log.info("token解析结果:{}",chain.filter(exchange));
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}